﻿using System;
using System.Collections.Generic;
using Google.Analytics.BusinessLogic.IDataAccess;
using Google.Analytics.Model;
using Google.Analytics.Model.Feeds;
using Google.Analytics.Model.Queries;

namespace Google.Analytics.BusinessLogic
{
    /// <summary>
    /// Formats queries and accesses the data layer -> cache and API
    /// </summary>
    public class DataManager
    {
        private readonly IAnalyticsDa analyticsDa;
        /// <summary>
        /// Creates a new <c>DataManager</c> object
        /// </summary>
        /// <param name="analyticsDa"></param>
        public DataManager(IAnalyticsDa analyticsDa)
        {
            this.analyticsDa = analyticsDa;
        }

        public IList<AccountEntry> GetAccounts(ref AuthState state)
        {
            VerifyState(ref state);

            //construct query
            var query = new AccountQuery(state);
            AccountFeed feed = analyticsDa.GetAccountFeed(query);
            IList<AccountEntry> accounts = new List<AccountEntry>();
            foreach (var entry in feed.Entries)
            {
                accounts.Add((AccountEntry)entry);
            }
            return accounts;
        }

        public IList<DataEntry> GetData(ref AuthState state, string accountID, IList<Dimensions> dimensions, IList<Metrics> metrics, string filter, IList<Order> order, DateTime startDate, DateTime stopDate)
        {
            //todo:validate the combinations
            
            
            VerifyState(ref state);

            //construct query
            var query = new DataQuery(state, accountID, startDate, stopDate, metrics, dimensions, order, filter);
            DataFeed feed = analyticsDa.GetDataFeed(query);
            IList<DataEntry> entries = new List<DataEntry>();
            foreach (var entry in feed.Entries)
            {
                entries.Add((DataEntry)entry);
            }
            return entries;
        }

        /// <summary>
        /// Check whether the Authentication has taken place
        /// </summary>
        /// <param name="state"></param>
        private void VerifyState(ref AuthState state)
        {
            if(string.IsNullOrEmpty(state.QueryAuthenticationToken))
            {
                state = analyticsDa.Authenticate(state);
            }
        }
    }
}
